document.getElementById('product-link').addEventListener('click', function () {
    showContent('product-edit');

    fetch('/product/manage', {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
        }
    })
        .then(response => response.json())
        .then(data => {
            var productManageDiv = document.getElementById('product-manage');
            productManageDiv.innerHTML = '<h2>产品管理界面</h2>';
            data.products.forEach(product => {
                productManageDiv.innerHTML += `
<table>
    <tr>
        <td>产品名称：</td>
        <td>${product.name}</td>
    </tr>
    <tr>
        <td>分类：</td>
        <td>${product.classify}</td>
    </tr>
    <tr>
        <td>图片：</td>
        <td><img src="${product.img}" alt="${product.name}" style="width:100px;height:auto;"></td>
    </tr>
    <tr>
        <td>详情：</td>
        <td>${product.detail}</td>
    </tr>
</table>
<button onclick="delete_product('${product.id}')" class="btn btn-lg btn-primary btn-block">删除产品</button>
<button onclick="update_product('${product.id}')" class="btn btn-lg btn-primary btn-block">更新产品</button>
<br>
`;
            });
        })
        .catch(error => {
            console.error('Error:', error);
        });
});

document.getElementById('add-product').addEventListener('click', function () {
    document.getElementById('product-form').style.display = 'block'; // 显示新增产品的表单
});

document.getElementById('submit-product').addEventListener('click', function () {
    var productData = {
        name: document.getElementById('product-name').value,
        classify: document.getElementById('product-classify').value,
        img: document.getElementById('product-img').value,
        detail: document.getElementById('product-detail').value
    };

    fetch('/product/create/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(productData)
    })
        .then(response => response.json())
        .then(data => {
            alert('产品新增成功！');
            document.getElementById('product-form').style.display = 'none'; // 隐藏表单
            location.reload();
        })
        .catch(error => {
            console.error('Error:', error);
            alert('新增失败，请重试！');
        });
});

function delete_product(productId) {
    fetch('/product/delete/' + productId + '/', {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json'
        }
    })
        .then(response => {
            if (response.ok) {
                location.reload();
            } else {
                throw new Error('删除产品失败');
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });
}